package zheezes.protocol.impl.gd;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import zheezes.util.Errno;


public class DataItemRegister {
	private static final Map<Short, DataItemDesc> map = new HashMap<Short, DataItemDesc>();

	static {
		InputStream in = DataItemRegister.class.getResourceAsStream("di.xml");
		SAXReader reader = new org.dom4j.io.SAXReader();
		Document doc = null;
		try {
			doc = reader.read(in);
		} catch (DocumentException e) {
			System.exit(Errno.EIO);
		}
		Element items = doc.getRootElement();
		short di;
		int size = 0;
		boolean inverse = true;
		String description = null;
		for (Object o : items.elements("di")) {
			Element item = (Element) o;
			Attribute attr = null;
			
			attr = item.attribute("id");
			di = (short) Integer.parseInt(attr.getValue(), 16);
			
			if ((attr = item.attribute("size")) != null) {
				size = Integer.parseInt(attr.getValue());
			}
			
			if ((attr = item.attribute("inverse")) != null) {
				inverse = Boolean.parseBoolean(attr.getValue());
			}
			
			if ((attr = item.attribute("description")) != null) {
				description = attr.getValue();
			}
			
			map.put(di, new DataItemDesc(di, size, inverse, description));
		}
		try {
			in.close();
		} catch (IOException e) {
		}
	}

	public static DataItemDesc query(short di) {
		return map.get(di);
	}

	public static void main(String[] args) {
		DataItemDesc desc = query((short) 0x8016);
		System.out.printf("%04X", desc.getDi());
	}
}
